package io.plus.server.utils;

import io.plus.common.io;
import io.plus.common.packet.metadata.Command;
import io.plus.common.packet.metadata.ResponseMessage;
import io.plus.common.protocol.Packet;
import io.plus.engine.pulse.AsynchronousSocketChannelContext;
import io.plus.engine.utils.lock.ReadWriteLockSet;
import io.plus.server.Status;
import io.plus.server.UserConfiguration;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatKit {


    /**
     * 聊天数据格式不正确响应包
     *
     * @param asynchronousSocketChannelContext
     * @return imPacket
     * @throws Exception
     */
    public static Packet dataInCorrectRespPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        ResponseMessage responseMessage = new ResponseMessage(Command.close_request, Status.C10002);
        Packet respPacket = ImKit.convertResponsepPacket(asynchronousSocketChannelContext, responseMessage);
        respPacket.setStatus(Status.C10002);
        return respPacket;
    }

    /**
     * 聊天发送成功响应包
     */
    public static Packet sendSuccessRespPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        ResponseMessage responseMessage = new ResponseMessage(Command.close_request, Status.ok);
        Packet respPacket = ImKit.convertResponsepPacket(asynchronousSocketChannelContext, responseMessage);
        respPacket.setStatus(Status.ok);
        return respPacket;
    }

    /**
     * 聊天用户不在线响应包
     */
    public static Packet offlineRespPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        ResponseMessage responseMessage = new ResponseMessage(Command.chat_response, Status.C10001);
        Packet respPacket = ImKit.convertResponsepPacket(asynchronousSocketChannelContext, responseMessage);
        respPacket.setStatus(Status.C10001);
        return respPacket;
    }

    /**
     * 判断用户是否在线
     */
    public static boolean isOnline(String userId, UserConfiguration userConfiguration) {
        boolean isStore = true;
        if (isStore) {
            return userConfiguration.getStore().isOnline(userId);
        }
        ReadWriteLockSet<AsynchronousSocketChannelContext> toChannelContexts = io.getChannelContextsByUserId(userId);
        return toChannelContexts != null && toChannelContexts.size() > 0;
    }


}
